//
// Created by Administrator on 2022/10/11.
//

#include "lock.h"

/* ================ start of thread.c ================ */
int init_pthread_rwlock(pthread_rwlock_t *rw_lock, const pthread_rwlockattr_t *attr) {
    int ret;

    ret = pthread_rwlock_init(rw_lock, attr);
    if(ret != 0 ) {
        printf("fail to pthread_rwlock_init\n");
        exit(EXIT_FAILURE);
    }
    return 0;
}
int init_rwlock(pthread_rwlock_t *rw_lock) {
    return init_pthread_rwlock(rw_lock, NULL);
}
/*
 * info:
 * 互斥锁的属性在创建锁的时候指定，在LinuxThreads实现中仅有一个锁类型属性，不同的锁类型在试图对一个已经被锁定的互斥锁加锁时表现不同。当前（glibc2.2.3,linuxthreads0.9）有四个值可供选择：
 * PTHREAD_MUTEX_TIMED_NP，这是缺省值，也就是普通锁。当一个线程加锁以后，其余请求锁的线程将形成一个等待队列，并在解锁后按优先级获得锁。这种锁策略保证了资源分配的公平性。
 * PTHREAD_MUTEX_RECURSIVE_NP，嵌套锁，允许同一个线程对同一个锁成功获得多次，并通过多次unlock解锁。如果是不同线程请求，则在加锁线程解锁时重新竞争。
 * PTHREAD_MUTEX_ERRORCHECK_NP，检错锁，如果同一个线程请求同一个锁，则返回EDEADLK，否则与PTHREAD_MUTEX_TIMED_NP类型动作相同。这样保证当不允许多次加锁时不出现最简单情况下的死锁。
 * PTHREAD_MUTEX_ADAPTIVE_NP，适应锁，动作最简单的锁类型，仅等待解锁后重新竞争。
 */
int init_pthread_lock(pthread_mutex_t *mutex_lock, const pthread_mutexattr_t *attr) {
    int ret = pthread_mutex_init(mutex_lock, attr);
    if(ret != 0 ) {
        printf("fail to pthread_mutex_init\n");
        exit(EXIT_FAILURE);
    }
    return 0;
}

int init_lock(pthread_mutex_t *mutex_lock) {
    return init_pthread_lock(mutex_lock, NULL);
}

int destroy_lock(pthread_mutex_t *mutex_lock) {
    return pthread_mutex_destroy(mutex_lock);
}

int init_pthread_cond(pthread_cond_t *cond) {
    int ret ;

    ret = pthread_cond_init(cond,NULL);
    if(ret != 0) {
        printf("fail to pthread_cond_init\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}

/* ================ end of thread.c ================ */
//或群读锁
int rwlock_rdlock(pthread_rwlock_t *lock)
{
    int err;
    err = pthread_rwlock_rdlock(lock);
    if(err == 0)
        return thread_ok;
    return thread_err;
}
//或群写锁
int rwlock_wrlock(pthread_rwlock_t *lock)
{
    int err;
    err = pthread_rwlock_wrlock(lock);
    if(err == 0)
        return thread_ok;
    return thread_err;
}
//
int rwlock_unlock(pthread_rwlock_t *lock)
{
    int err;
    err = pthread_rwlock_unlock(lock);
    if(err == 0)
        return thread_ok;
    return thread_err;
}
// 获取线程锁
int mutex_lock(pthread_mutex_t *lock)
{
    int err;
    err = pthread_mutex_lock(lock);
    if(err == 0)
        return thread_ok;
    return thread_err;
}
// 释放线程锁
int mutex_unlock(pthread_mutex_t *lock)
{
    int err;
    err = pthread_mutex_unlock(lock);
    if(err == 0)
        return thread_ok;
    return thread_err;
}